/**  
* @Title: MtonsMessageUtils.java
* @Package cn.net.mtons.weixin.utils
* @Description: TODO
* @author ma jinjian  
* @date 2016年2月7日 下午1:31:13
* @version V1.0  
*/ 
package cn.net.mtons.weixin.utils;

import java.util.Map;

/**
 * @ClassName: MtonsMessageUtils
 * @Description: TODO
 * @author ma jinjian
 * @date 2016年2月7日 下午1:31:13
 *
 */
public class MtonsMessageUtil {
	
    private StringBuilder builder;

    public MtonsMessageUtil() {
        builder = new StringBuilder();
    }

    public MtonsMessageUtil(int capacity) {
        builder = new StringBuilder(capacity);
    }

    public MtonsMessageUtil(String str) {
        builder = new StringBuilder(str);
    }

    public void append(String str) {
        builder.append(str);
    }

    public void insert(String str) {
        builder.insert(0, str);
    }

    public void surroundWith(String tag) {
        StringBuilder sb = new StringBuilder(builder.capacity() + tag.length()
                * 2 + 5);
        sb.append("<").append(tag).append(">\n").append(builder).append("</")
                .append(tag).append(">\n");
        builder = sb;
    }

    public void addTag(String tagName, String text) {
        if (text == null) {
            return;
        }
        builder.append("<").append(tagName).append(">").append(text)
                .append("</").append(tagName).append(">\n");
    }

    public void addData(String tagName, Object data) {
        if (data == null) {
            return;
        }
        if(tagName.equals("CreateTime") || tagName.equals("ArticleCount")){
        	builder.append("<").append(tagName).append(">").append(data)
            .append("></").append(tagName).append(">\n");
        }else{
        	builder.append("<").append(tagName).append("><![CDATA[").append(data)
            .append("]]></").append(tagName).append(">\n");
        }
    }
    
    public void addData(String tagName, String subTag, String data){
    	 if (data == null) {
             return;
         }
        builder.append("<"+tagName+">\n")
         			.append("<"+subTag+">")
         				.append("<![CDATA["+data+"]]>")
         			.append("</"+subTag+">\n")
         		.append("</"+tagName+">\n");
    }
    
    public void addData(String tagName, Map<String, String> map){
    	builder.append("<"+tagName+">\n");
    	for(Map.Entry<String, String> entry : map.entrySet()){
    		builder.append("<"+entry.getKey()+"><![CDATA[").append(entry.getValue()).append("]]></"+entry.getKey()+">\n");
    	}
    	builder.append("</"+tagName+">\n");
    }

    @Override
    public String toString() {
        return builder.toString();
    }

}
